package com.base.common;

import java.text.SimpleDateFormat;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.Inject;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.component.ajax.AjaxUpdater;
import org.operamasks.faces.component.layout.impl.UIPanel;
import org.operamasks.faces.user.ajax.PartialUpdateManager;
import org.operamasks.faces.user.util.Browser;

import com.base.commons.SpringBeanHolder;
import com.base.security.onlineuser.entity.MaxOnlineUser;
import com.base.security.onlineuser.service.UserLoginHandler;

@ManagedBean(name = "mainBean", scope = ManagedBeanScope.REQUEST)
public class MainBean {
	private UserLoginHandler userLoginHandler = SpringBeanHolder
			.getBean("userLoginHandler");
	@Inject
	private FacesContext context;
	@Inject
	private PartialUpdateManager update;

	@Bind
	public String onlineUserCount;

	@Bind
	public String highestOnlineUserCount;
	@Bind(id = "menuUpdater")
	public AjaxUpdater menuUpdater;
	@Bind(id = "menuPanel")
	public UIPanel menuPanel;

	@BeforeRender
	public void beforeRender(boolean isPostback) throws Exception {
		if (!isPostback) {
			this.updateOnlineUserCount();
		}
	}

	public String menuAction(UIComponent item) throws Exception {
		String value = (String) item.getAttributes().get("value");
		String name = (String) item.getAttributes().get("label");
		System.out.println("----:" + value + "---:" + name);
		if (value == null || "".equals(value)) {
		}
		menuUpdater.load(value);
		menuPanel.setTitle(name);
		// 展开模块菜单
		Browser.execClientScript("window.top",
				"moduleMenusPanelJsvar.expand();");
		return null;
	}

	public void updateOnlineUserCount() {
		onlineUserCount = String.valueOf(userLoginHandler.getOnlineUserCount());
		MaxOnlineUser mou = userLoginHandler.getMaxOnlineUser();
		if (mou == null)
			highestOnlineUserCount = "0";
		else {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			highestOnlineUserCount = mou.getUserCount() + "（"
					+ sdf.format(mou.getCurrentDate()) + "）";
		}
		update.markAttributeUpdate("onlineUserCount", "value");
		update.markAttributeUpdate("highestOnlineUserCount", "value");
	}

}
